<template>
  <div class="password-form-container">
    <form class="password-form" @submit.prevent>
      <div class="form-group">
        <label class="form-label" for="old-password">
          <span class="form-label-text">旧密码</span>
          <div
            class="input-wrapper"
            :class="{
              'is-error': errors.old_password,
              'is-focused': focused.old_password,
            }"
          >
            <span class="input-icon iconfont icon-mima"></span>
            <input
              id="old-password"
              type="password"
              v-model="formData.old_password"
              placeholder="请输入旧密码"
              @focus="focused.old_password = true"
              @blur="
                validateField('old_password');
                focused.old_password = false;
              "
            />
          </div>
          <p class="error-message" v-if="errors.old_password">
            {{ errors.old_password }}
          </p>
        </label>
      </div>

      <div class="form-group">
        <label class="form-label" for="new-password">
          <span class="form-label-text">新密码</span>
          <div
            class="input-wrapper"
            :class="{
              'is-error': errors.new_password,
              'is-focused': focused.new_password,
            }"
          >
            <span class="input-icon iconfont icon-mimazhongzhi"></span>
            <input
              id="new-password"
              type="password"
              v-model="formData.new_password"
              placeholder="请输入新密码"
              @focus="focused.new_password = true"
              @blur="
                validateField('new_password');
                focused.new_password = false;
              "
            />
          </div>
          <p class="error-message" v-if="errors.new_password">
            {{ errors.new_password }}
          </p>
        </label>
      </div>

      <div class="form-group">
        <label class="form-label" for="confirm-password">
          <span class="form-label-text">确认密码</span>
          <div
            class="input-wrapper"
            :class="{
              'is-error': errors.confirm_password,
              'is-focused': focused.confirm_password,
            }"
          >
            <span class="input-icon iconfont icon-mimazhongzhi"></span>
            <input
              id="confirm-password"
              type="password"
              v-model="formData.confirm_password"
              placeholder="请再次输入新密码"
              @focus="focused.confirm_password = true"
              @blur="
                validateField('confirm_password');
                focused.confirm_password = false;
              "
            />
          </div>
          <p class="error-message" v-if="errors.confirm_password">
            {{ errors.confirm_password }}
          </p>
        </label>
      </div>
      <div class="password-strength" v-if="formData.new_password">
        <div class="strength-label">密码强度:</div>
        <div class="strength-meter">
          <div
            class="strength-bar"
            :style="{
              width: passwordStrength.percent + '%',
              backgroundColor: passwordStrength.color,
            }"
          ></div>
        </div>
        <div class="strength-text" :style="{ color: passwordStrength.color }">
          {{ passwordStrength.text }}
        </div>
      </div>
    </form>
  </div>
</template>

<script>
export default {
  name: "PasswordForm",
  props: {
    modelValue: {
      type: Object,
      default: () => ({
        old_password: "",
        new_password: "",
        confirm_password: "",
      }),
    },
  },
  emits: ["update:modelValue", "validate"],
  data () {
    return {
      formData: {
        old_password: "",
        new_password: "",
        confirm_password: "",
      },
      focused: {
        old_password: false,
        new_password: false,
        confirm_password: false,
      },
      errors: {
        old_password: "",
        new_password: "",
        confirm_password: "",
      },
    };
  },
  computed: {
    passwordStrength () {
      const password = this.formData.new_password;
      if (!password) {
        return {
          percent: 0,
          color: "#e0e0e0",
          text: "无",
        };
      }

      let strength = 0;
      // Length contribution
      strength += Math.min(6, Math.floor(password.length / 3)) * 10;

      // Character variety contribution
      if (/[a-z]/.test(password)) strength += 10;
      if (/[A-Z]/.test(password)) strength += 10;
      if (/\d/.test(password)) strength += 10;
      if (/[^a-zA-Z0-9]/.test(password)) strength += 15;

      // Classify strength
      let color = "";
      let text = "";

      if (strength < 30) {
        color = "#FF4949";
        text = "弱";
      } else if (strength < 60) {
        color = "#E6A23C";
        text = "中";
      } else {
        color = "#67C23A";
        text = "强";
      }

      return {
        percent: Math.min(100, strength),
        color,
        text,
      };
    },
  },
  watch: {
    modelValue: {
      handler (val) {
        // 避免循环更新：只有当值真的不同时才更新
        if (JSON.stringify(val) !== JSON.stringify(this.formData)) {
          this.formData = { ...val };
        }
      },
      immediate: true,
      deep: true,
    },
    formData: {
      handler (val) {
        // 避免循环更新：只有当值真的不同时才发射事件
        if (JSON.stringify(val) !== JSON.stringify(this.modelValue)) {
          this.$emit("update:modelValue", { ...val });
        }
      },
      deep: true,
    },
  },
  methods: {
    validateField (field) {
      this.errors[field] = "";

      switch (field) {
      case "old_password":
        if (!this.formData.old_password) {
          this.errors.old_password = "请输入旧密码";
        }
        break;

      case "new_password":
        if (!this.formData.new_password) {
          this.errors.new_password = "请输入新密码";
        } else if (this.formData.new_password.length < 6) {
          this.errors.new_password = "新密码不能低于6位数";
        }

        // If confirm_password has been entered, validate it again
        if (this.formData.confirm_password) {
          this.validateField("confirm_password");
        }
        break;

      case "confirm_password":
        if (!this.formData.confirm_password) {
          this.errors.confirm_password = "请输入确认密码";
        } else if (
          this.formData.new_password !== this.formData.confirm_password
        ) {
          this.errors.confirm_password = "确认密码与新密码不一致，请重新输入";
        }
        break;
      }

      return !this.errors[field];
    },

    validate () {
      // Validate all fields
      const isOldPasswordValid = this.validateField("old_password");
      const isNewPasswordValid = this.validateField("new_password");
      const isConfirmPasswordValid = this.validateField("confirm_password");

      const isValid =
        isOldPasswordValid && isNewPasswordValid && isConfirmPasswordValid;
      this.$emit("validate", isValid);
      return isValid;
    },
  },
};
</script>

<style scoped lang="less">
.password-form-container {
  width: 100%;

  .password-form {
    .form-group {
      margin-bottom: 24px;

      .form-label {
        display: block;

        .form-label-text {
          display: block;
          margin-bottom: 8px;
          font-size: 14px;
          color: #606266;
          text-align: left;
          font-weight: 500;
        }
        .input-wrapper {
          display: flex;
          align-items: center;
          background: #f5f7fa;
          border-radius: 8px;
          border: 1px solid transparent;
          padding: 0 15px;
          height: 42px;
          transition: all 0.3s ease;
          position: relative;
          overflow: hidden;

          &:before {
            content: "";
            position: absolute;
            bottom: 0;
            left: 0;
            height: 2px;
            width: 0;
            background: linear-gradient(to right, #4b58dc, #7b86ff);
            transition: width 0.3s ease;
          }

          &.is-focused {
            border-color: rgba(75, 88, 220, 0.3);
            background: #fff;
            box-shadow: 0 0 0 3px rgba(75, 88, 220, 0.1);

            &:before {
              width: 100%;
            }

            .input-icon {
              color: #4b58dc;
            }
          }

          &.is-error {
            border-color: #ff4949;

            &:before {
              background: #ff4949;
            }
          }

          .input-icon {
            margin-right: 10px;
            font-size: 16px;
            color: #909399;
            transition: color 0.3s ease;
          }

          input {
            flex: 1;
            border: none;
            background: none;
            outline: none;
            height: 100%;
            color: #303133;
            font-size: 14px;

            &::placeholder {
              color: #c0c4cc;
            }
          }
        }

        .error-message {
          margin: 5px 0 0;
          font-size: 12px;
          color: #ff4949;
          animation: errorShake 0.3s ease-in-out;
        }
      }
    }

    .password-strength {
      margin-top: 15px;
      padding-top: 15px;
      border-top: 1px dashed rgba(75, 88, 220, 0.1);

      .strength-label {
        font-size: 13px;
        color: #606266;
        margin-bottom: 8px;
      }

      .strength-meter {
        height: 6px;
        background: #e0e0e0;
        border-radius: 3px;
        overflow: hidden;
        margin-bottom: 6px;

        .strength-bar {
          height: 100%;
          border-radius: 3px;
          transition: all 0.5s ease;
        }
      }

      .strength-text {
        font-size: 12px;
        font-weight: 500;
        text-align: right;
      }
    }
  }
}

@keyframes errorShake {
  0%,
  100% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(-5px);
  }
  75% {
    transform: translateX(5px);
  }
}
</style>
